package com.dingwei.lesyndrome.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperTextView;
import com.dingwei.lesyndrome.R;
import com.dingwei.lesyndrome.adapter.CircleGridAdapter;
import com.dingwei.lesyndrome.app.MyApplication;
import com.dingwei.lesyndrome.bean.GamCircleTypeBean;
import com.dingwei.lesyndrome.mvp.presenter.AddCirclePresenter;
import com.dingwei.lesyndrome.mvp.view.Contract;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.L;
import com.lihao.baselibrary.weight.TitleBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/3/2.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */

public class AddCircleActivity extends BaseActivity implements Contract.AddCircleView {

    AddCirclePresenter addCirclePresenter = new AddCirclePresenter(this);
    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.edt_content)
    EditText edtContent;
    @Bind(R.id.img_pic)
    ImageView imgPic;
    @Bind(R.id.img_video)
    ImageView imgVideo;
    @Bind(R.id.ll_choose)
    LinearLayout llChoose;
    @Bind(R.id.grid_pics)
    RecyclerView gridPics;
    @Bind(R.id.img_top)
    ImageView imgTop;
    @Bind(R.id.fl_video)
    FrameLayout flVideo;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.img_address)
    ImageView imgAddress;

    CircleGridAdapter adapter;
    @Bind(R.id.check_type)
    SuperTextView checkType;
    private GamCircleTypeBean typeBean;

    private List<LocalMedia> photoList = new ArrayList<>();
    String videoPath;
    boolean open;

    String checkTypeId = "";

    @Override
    protected int getContentViewId() {
        return R.layout.activity_add_circle;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

        typeBean = (GamCircleTypeBean) getIntent().getSerializableExtra("typeBean");
        checkType.setRightString(typeBean.data.get(0).name);
        checkTypeId = typeBean.data.get(0).id;

        adapter = new CircleGridAdapter(BaseActivity.context);
        tvAddress.setText(MyApplication.location.getCity()+ "·" + MyApplication.location.getStreet());
        GridLayoutManager layoutManager = new GridLayoutManager(BaseActivity.context, 4);
        layoutManager.setSpanSizeLookup(adapter.obtainGridSpanSizeLookUp(4));
        SpaceDecoration itemDecoration = new SpaceDecoration((int) DisplayUtil.dip2px(BaseActivity.context, 10));//参数是距离宽度
        itemDecoration.setPaddingEdgeSide(false);//是否为左右2边添加padding.默认true.
        itemDecoration.setPaddingStart(false);//是否在给第一行的item添加上padding(不包含header).默认true.
        itemDecoration.setPaddingHeaderFooter(false);//是否对Header于Footer有效,默认false.

        gridPics.setLayoutManager(layoutManager);
        gridPics.setAdapter(adapter);
        gridPics.setNestedScrollingEnabled(false);
        gridPics.addItemDecoration(itemDecoration);


        adapter.onChooseImgInterFaceListener(new CircleGridAdapter.ChooseImgInterFace() {
            @Override
            public void onPicClick(int position) {
                LocalMedia localMedia = photoList.get(position);
                if (!TextUtils.isEmpty(localMedia.getCompressPath())) {
                    List<LocalMedia> localMediaList = new ArrayList<>();
                    localMediaList.addAll(photoList);
                    for (int i = 0; i < photoList.size(); i++) {
                        if (TextUtils.isEmpty(photoList.get(i).getCompressPath())) {
                            localMediaList.remove(i);
                            break;
                        }
                    }
                    PictureSelector.create(AddCircleActivity.this).externalPicturePreview(position, localMediaList);
                } else {
                    List<LocalMedia> localMediaList = new ArrayList<>();
                    localMediaList.addAll(photoList);
                    for (int i = 0; i < photoList.size(); i++) {
                        if (TextUtils.isEmpty(photoList.get(i).getCompressPath())) {
                            localMediaList.remove(i);
                            break;
                        }
                    }
                    PictureSelector.create(AddCircleActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .theme(R.style.picture_white_style)
                            .imageSpanCount(3)
                            .maxSelectNum(6)
                            .selectionMode(PictureConfig.MULTIPLE)
                            .previewImage(true)
                            .isCamera(true)
                            .isZoomAnim(true)
                            .selectionMedia(localMediaList)
                            .enableCrop(false)// 是否裁剪 true or false
                            .compress(true)// 是否压缩 true or false
                            .previewEggs(true) // 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                            .minimumCompressSize(100) // 小于100kb的图片不压缩
                            .forResult(1001);
                }

            }

            @Override
            public void onRemoveClick(int position) {
                photoList.remove(position);
                adapter.remove(position);
                if (!TextUtils.isEmpty(adapter.getAllData().get(adapter.getAllData().size()-1).getCompressPath())){
                    adapter.add(new LocalMedia());
                }
                photoList.clear();
                photoList = adapter.getAllData();
            }
        });

        titleBar.setOnMenuListener(new TitleBar.OnMenuListener() {
            @Override
            public void onMenuClick() {
              addCirclePresenter.commitVideo(checkTypeId,edtContent.getText().toString(),open,videoPath,photoList);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.img_pic, R.id.img_video, R.id.fl_video, R.id.img_address,R.id.check_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_pic:
                List<LocalMedia> localMediaList = new ArrayList<>();
                localMediaList.addAll(photoList);
                for (int i = 0; i < photoList.size(); i++) {
                    if (TextUtils.isEmpty(photoList.get(i).getCompressPath())) {
                        localMediaList.remove(i);
                        break;
                    }
                }
                PictureSelector.create(AddCircleActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_white_style)
                        .imageSpanCount(3)
                        .maxSelectNum(6)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .previewImage(true)
                        .isCamera(true)
                        .isZoomAnim(true)
                        .selectionMedia(localMediaList)
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .previewEggs(true) // 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .minimumCompressSize(100) // 小于100kb的图片不压缩
                        .forResult(1001);
                break;
            case R.id.img_video:
                PictureSelector.create(AddCircleActivity.this)
                        .openGallery(PictureMimeType.ofVideo())
                        .theme(R.style.picture_white_style)
                        .selectionMode(PictureConfig.SINGLE)
                        .isCamera(true)
                        .compress(true)
                        .videoQuality(0)
                        .synOrAsy(true)
                        .videoMaxSecond(15)
                        .recordVideoSecond(15)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.fl_video:
                PictureSelector.create(AddCircleActivity.this).externalPictureVideo(videoPath);
                break;
            case R.id.img_address:
                open = !open;
                if (open) {
                    imgAddress.setImageResource(R.drawable.ic_open);
                } else {
                    imgAddress.setImageResource(R.drawable.ic_normal);
                }
                break;
            case R.id.check_type:
                addCirclePresenter.showChooseTypeDialog(this,typeBean);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                LocalMedia localMedia = selectList.get(0);
                L.e(" path = " + localMedia.getPath() + "   getCompressPath = " + localMedia.getCompressPath());
                videoPath = localMedia.getPath();

                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(videoPath);
                String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                try {
                    int lenth = Integer.valueOf(duration) / 1000;
                    if (lenth <= 15) {
                        flVideo.setVisibility(View.VISIBLE);
                        llChoose.setVisibility(View.GONE);
                        Bitmap bitmap = mmr.getFrameAtTime();
                        imgTop.setImageBitmap(bitmap);
                    } else {
                        showToast("视频过长请重新选择");
                    }
                } catch (Exception e) {
                    L.e("video error = " + e);
                    showToast("视频资源异常");
                }
            } else if (requestCode == 1001) {
                if (data != null) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    photoList.clear();
                    for (LocalMedia localMedia : selectList) {
                        if (!TextUtils.isEmpty(localMedia.getCompressPath())) {
                            photoList.add(localMedia);
                        }

                    }
                    photoList.add(new LocalMedia());
                    if (photoList.size() == 7) {
                        photoList.remove(photoList.size() - 1);
                    }
                    if (photoList.size() == 1) {
                        photoList.clear();
                    }

                    refreshPic();
                }
            }
        }
    }

    private void refreshPic() {
        if (photoList == null && photoList.size() <= 0) {
            gridPics.setVisibility(View.GONE);
            llChoose.setVisibility(View.VISIBLE);
        } else {
            gridPics.setVisibility(View.VISIBLE);
            llChoose.setVisibility(View.GONE);
        }
        adapter.clear();
        adapter.addAll(photoList);
    }

    @Override
    public void selectType(GamCircleTypeBean.DataBean data) {
        checkType.setRightString(data.name);
        checkTypeId = data.id;
    }

    @Override
    public void submitSuccess() {
        setResult(RESULT_OK);
        finish();
    }
}
